import React, { useEffect, useState, useRef, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Box,
  Paper,
  Typography,
  Grid,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  CircularProgress,
  Snackbar,
  Alert,
  IconButton,
  InputAdornment,
  Tooltip,
  LinearProgress,
  Tabs,
  Tab,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Divider,
  Stack,
  useTheme,
  useMediaQuery,
  Card,
  CardContent,
  Chip,
  TableContainer,
  Table,
  TableHead,
  TableBody,
  TableCell,
  TableRow,
} from '@mui/material';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';
import {
  ArrowBack as ArrowBackIcon,
  Visibility as VisibilityIcon,
  VisibilityOff as VisibilityOffIcon,
  Refresh as RefreshIcon,
  SystemUpdate as SystemUpdateIcon,
  Lock as LockIcon,
  Settings as SettingsIcon,
  Upload as UploadIcon,
  Download as DownloadIcon,
  FilterList as FilterListIcon,
  Wifi as WifiIcon,
  WifiOff as WifiOffIcon,
} from '@mui/icons-material';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import apiClient from '../services/apiService';
import { websocketService } from '../services/websocketService';
import { format, parseISO } from 'date-fns';
import { saveAs } from 'file-saver';
import TemperatureHumidityChart from '../components/TemperatureHumidityChart';
import { Device, DeviceData, DeviceConfig } from '../types/device';
import Papa from 'papaparse';

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api';

type ConfigSection = keyof DeviceConfig;
type AlarmParam = keyof DeviceConfig['alarmThresholds'];
type AlarmThreshold = keyof DeviceConfig['alarmThresholds']['temperature'];

interface DateRange {
  startDate: string;
  endDate: string;
}

const DeviceDetail: React.FC = () => {
  const { deviceId } = useParams<{ deviceId: string }>();
  const navigate = useNavigate();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const isTablet = useMediaQuery(theme.breakpoints.down('md'));
  const [device, setDevice] = useState<Device | null>(null);
  const [deviceData, setDeviceData] = useState<DeviceData[]>([]);
  const [openPasswordDialog, setOpenPasswordDialog] = useState(false);
  const [openConfirmDialog, setOpenConfirmDialog] = useState(false);
  const [newPassword, setNewPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [confirmAction, setConfirmAction] = useState<'restart' | 'update' | null>(null);
  const [snackbar, setSnackbar] = useState<{
    open: boolean;
    message: string;
    severity: 'success' | 'error';
  }>({
    open: false,
    message: '',
    severity: 'success',
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [firmwareFile, setFirmwareFile] = useState<File | null>(null);
  const [updateProgress, setUpdateProgress] = useState(0);
  const [isUpdating, setIsUpdating] = useState(false);
  const [config, setConfig] = useState<DeviceConfig | null>(null);
  const [configTab, setConfigTab] = useState(0);
  const [showWifiPassword, setShowWifiPassword] = useState(false);
  const [showMqttPassword, setShowMqttPassword] = useState(false);
  const [fileType, setFileType] = useState('config');
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [dateRange, setDateRange] = useState<DateRange>({
    startDate: '',
    endDate: '',
  });
  const [filteredData, setFilteredData] = useState<DeviceData[]>([]);
  const [showFilter, setShowFilter] = useState(false);
  const [openConfigDialog, setOpenConfigDialog] = useState(false);

  const fetchDevice = useCallback(async () => {
    if (!deviceId) return;
    
    try {
      setLoading(true);
      const response = await apiClient.get(`/devices/${deviceId}`);
      setDevice(response.data);
      setError(null);
    } catch (error: any) {
      console.error('获取设备信息失败:', error);
      setError(error.response?.data?.message || '获取设备信息失败');
    } finally {
      setLoading(false);
    }
  }, [deviceId]);

  const fetchDeviceData = useCallback(async () => {
    if (!deviceId) return;

    try {
      const response = await apiClient.get(`/devices/${deviceId}/data`, {
        params: {
          startDate: dateRange.startDate,
          endDate: dateRange.endDate,
        },
      });
      setDeviceData(response.data);
      setFilteredData(response.data);
    } catch (error: any) {
      console.error('获取设备数据失败:', error);
      setError(error.response?.data?.message || '获取设备数据失败');
    }
  }, [deviceId, dateRange]);

  const fetchDeviceConfig = useCallback(async () => {
    try {
      const response = await apiClient.get(`/devices/${deviceId}/config`);
      setConfig(response.data);
    } catch (error: any) {
      setError(error.response?.data?.message || '获取设备配置失败');
    }
  }, [deviceId]);

  const applyFilters = useCallback(() => {
    if (!deviceData.length) return;
    
    let filtered = [...deviceData];
    const timezoneOffset = new Date().getTimezoneOffset() * 60000;

    if (dateRange.startDate) {
      const startDate = new Date(dateRange.startDate);
      filtered = filtered.filter(
        data => new Date(data.timestamp).getTime() >= startDate.getTime() - timezoneOffset
      );
    }

    if (dateRange.endDate) {
      const endDate = new Date(dateRange.endDate);
      filtered = filtered.filter(
        data => new Date(data.timestamp).getTime() <= endDate.getTime() - timezoneOffset
      );
    }

    // 按时间戳排序
    filtered.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());

    setFilteredData(filtered);
  }, [deviceData, dateRange]);

  // 获取当天的开始和结束时间
  const getTodayRange = useCallback(() => {
    const now = new Date();
    // 获取本地时区的偏移量（分钟）
    const timezoneOffset = now.getTimezoneOffset();
    
    // 创建本地时间的开始和结束时间
    const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
    const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
    
    // 转换为ISO字符串并调整时区
    const formatDate = (date: Date) => {
      const localDate = new Date(date.getTime() - timezoneOffset * 60000);
      return localDate.toISOString().slice(0, 16);
    };
    
    return {
      startDate: formatDate(startOfDay),
      endDate: formatDate(endOfDay)
    };
  }, []);

  // 初始化日期范围
  useEffect(() => {
    const todayRange = getTodayRange();
    setDateRange(todayRange);
  }, [getTodayRange]);

  // 优化初始化数据加载
  useEffect(() => {
    if (deviceId) {
      fetchDevice();
      fetchDeviceData();
      fetchDeviceConfig();
    }
  }, [deviceId, fetchDevice, fetchDeviceData, fetchDeviceConfig]);

  // 处理数据筛选
  useEffect(() => {
    applyFilters();
  }, [applyFilters]);

  // 优化 WebSocket 订阅
  useEffect(() => {
    if (!deviceId) return;

    // 设备状态实时更新
    const handleDeviceUpdate = (data: any) => {
      if (data.deviceId === deviceId) {
        setDevice(prev => ({
          ...prev!,
          status: data.status,
          lastHeartbeat: data.lastHeartbeat || data.metadata?.lastSeen,
          temperature: data.temperature || data.data?.temperature,
          humidity: data.humidity || data.data?.humidity,
          updatedAt: new Date().toISOString()
        }));

        // 如果是数据更新事件，添加到数据列表
        if (data.type === 'device_data_update') {
          setDeviceData(prev => {
            const newData = [...prev];
            const index = newData.findIndex(item => item.timestamp === data.timestamp);
            if (index >= 0) {
              newData[index] = data;
            } else {
              newData.push(data);
            }
            return newData.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
          });
        }
      }
    };

    // 订阅设备状态更新
    websocketService.subscribe('device_status_change', handleDeviceUpdate);
    websocketService.subscribe('device_status_broadcast', handleDeviceUpdate);
    websocketService.subscribe('device_data_update', handleDeviceUpdate);

    // 设置数据定时刷新
    const dataRefreshInterval = setInterval(() => {
      fetchDeviceData();
    }, 10000); // 每10秒刷新一次数据

    return () => {
      websocketService.unsubscribe('device_status_change', handleDeviceUpdate);
      websocketService.unsubscribe('device_status_broadcast', handleDeviceUpdate);
      websocketService.unsubscribe('device_data_update', handleDeviceUpdate);
      clearInterval(dataRefreshInterval);
    };
  }, [deviceId, fetchDeviceData]);

  const handleUpdatePassword = async () => {
    try {
      await apiClient.put(`/devices/${deviceId}/password`, {
        password: newPassword,
      });
      setSnackbar({
        open: true,
        message: '密码更新成功',
        severity: 'success',
      });
      setOpenPasswordDialog(false);
      setNewPassword('');
    } catch (error: any) {
      setSnackbar({
        open: true,
        message: error.response?.data?.message || '密码更新失败',
        severity: 'error',
      });
    }
  };

  const handleSendCommand = async (command: string) => {
    try {
      await apiClient.post(`/devices/${deviceId}/command`, {
        command,
        params: {},
      });
      setOpenConfirmDialog(false);
      setConfirmAction(null);
      setSnackbar({
        open: true,
        message: command === 'restart' ? '重启命令已发送' : '固件更新命令已发送',
        severity: 'success',
      });
    } catch (error: any) {
      setError(error.response?.data?.message || '发送命令失败');
      setSnackbar({
        open: true,
        message: error.response?.data?.message || '发送命令失败',
        severity: 'error',
      });
    }
  };

  const handleConfirmAction = (action: 'restart' | 'update') => {
    setConfirmAction(action);
    setOpenConfirmDialog(true);
  };

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('fileType', fileType);

      apiClient.post(`/devices/${deviceId}/file`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then(() => {
        setSnackbar({
          open: true,
          message: '文件发送成功',
          severity: 'success',
        });
      })
      .catch((error) => {
        setSnackbar({
          open: true,
          message: error.response?.data?.message || '文件发送失败',
          severity: 'error',
        });
      });
    }
  };

  const handleConfigChange = (section: ConfigSection, field: string, value: any) => {
    if (!config) return;

    setConfig(prev => {
      if (!prev) return prev;
      const newConfig = { ...prev };
      
      if (section === 'alarmThresholds') {
        const [param, threshold] = field.split('.') as [AlarmParam, AlarmThreshold];
        if (param in newConfig.alarmThresholds && threshold in newConfig.alarmThresholds[param]) {
          newConfig.alarmThresholds[param][threshold] = Number(value);
        }
      } else if (section in newConfig) {
        const sectionConfig = newConfig[section] as Record<string, any>;
        if (field in sectionConfig) {
          sectionConfig[field] = value;
        }
      }
      
      return newConfig;
    });
  };

  const handleSaveConfig = async () => {
    try {
      setLoading(true);
      const response = await apiClient.put(`/devices/${deviceId}/config`, config);
      setSnackbar({
        open: true,
        message: response.data.message || '配置更新成功',
        severity: 'success',
      });
      setOpenConfigDialog(false);
    } catch (error: any) {
      setSnackbar({
        open: true,
        message: error.response?.data?.message || '配置更新失败',
        severity: 'error',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleUpdateFirmware = async () => {
    if (!firmwareFile) {
      setSnackbar({
        open: true,
        message: '请选择固件文件',
        severity: 'error',
      });
      return;
    }

    try {
      setIsUpdating(true);
      const formData = new FormData();
      formData.append('firmware', firmwareFile);

      await apiClient.post(`/devices/${deviceId}/firmware`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: (progressEvent) => {
          const progress = progressEvent.total
            ? Math.round((progressEvent.loaded * 100) / progressEvent.total)
            : 0;
          setUpdateProgress(progress);
        },
      });

      setSnackbar({
        open: true,
        message: '固件更新成功',
        severity: 'success',
      });
      setOpenConfirmDialog(false);
      setFirmwareFile(null);
      setUpdateProgress(0);
    } catch (error: any) {
      setSnackbar({
        open: true,
        message: error.response?.data?.message || '固件更新失败',
        severity: 'error',
      });
    } finally {
      setIsUpdating(false);
    }
  };

  const handleExportData = () => {
    if (!filteredData.length) return;

    const csvData = filteredData.map(data => ({
      时间: format(parseISO(data.timestamp), 'yyyy-MM-dd HH:mm:ss'),
      温度: data.data.temperature,
      湿度: data.data.humidity,
      电池电量: data.data.battery,
      信号强度: data.data.signal,
    }));

    const csv = Papa.unparse(csvData);
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
    saveAs(blob, `device_data_${deviceId}_${format(new Date(), 'yyyyMMdd_HHmmss')}.csv`);
  };

  const handleDateRangeChange = (field: keyof DateRange, value: string) => {
    const timezoneOffset = new Date().getTimezoneOffset() * 60000;
    const date = parseISO(value);
    const adjustedDate = new Date(date.getTime() - timezoneOffset);
    
    setDateRange(prev => ({
      ...prev,
      [field]: format(adjustedDate, "yyyy-MM-dd'T'HH:mm")
    }));
  };

  const handleResetFilters = () => {
    setDateRange({
      startDate: '',
      endDate: '',
    });
  };

  // 修改设备配置按钮的点击处理
  const handleConfigClick = () => {
    setOpenConfigDialog(true);
  };

  const handleUpdateConfig = async (config: DeviceConfig | null) => {
    if (!config) {
      setSnackbar({
        open: true,
        message: '配置数据无效',
        severity: 'error',
      });
      return;
    }

    try {
      await apiClient.put(`/devices/${deviceId}/config`, config);
      setSnackbar({
        open: true,
        message: '配置更新成功',
        severity: 'success',
      });
      setOpenConfigDialog(false);
    } catch (error: any) {
      setSnackbar({
        open: true,
        message: error.response?.data?.message || '配置更新失败',
        severity: 'error',
      });
    }
  };

  // 修改设备操作按钮的渲染逻辑
  const renderDeviceActions = () => {
    if (!device) return null;
    
    return (
      <Grid container spacing={2}>
        <Grid item xs={12} sm={6} md={3}>
          <Button
            fullWidth
            variant="outlined"
            startIcon={<RefreshIcon />}
            onClick={() => handleConfirmAction('restart')}
            size={isMobile ? "small" : "medium"}
            disabled={device.status === 'offline'}
          >
            重启设备
          </Button>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Button
            fullWidth
            variant="outlined"
            startIcon={<LockIcon />}
            onClick={() => setOpenPasswordDialog(true)}
            size={isMobile ? "small" : "medium"}
            disabled={device.status === 'offline'}
          >
            修改密码
          </Button>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Button
            fullWidth
            variant="outlined"
            startIcon={<SystemUpdateIcon />}
            onClick={() => handleConfirmAction('update')}
            size={isMobile ? "small" : "medium"}
            disabled={device.status === 'offline'}
          >
            更新固件
          </Button>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Button
            fullWidth
            variant="outlined"
            startIcon={<SettingsIcon />}
            onClick={handleConfigClick}
            size={isMobile ? "small" : "medium"}
          >
            设备配置
          </Button>
        </Grid>
      </Grid>
    );
  };

  // 修改数据图表和过滤器的渲染逻辑
  const renderDataChart = () => {
    if (!device) return null;
    
    return (
      <Card sx={{ mb: { xs: 2, sm: 3 } }}>
        <CardContent>
          <Box sx={{ 
            display: 'flex', 
            justifyContent: 'space-between',
            alignItems: 'center',
            mb: 2,
            flexDirection: { xs: 'column', sm: 'row' },
            gap: { xs: 2, sm: 0 }
          }}>
            <Typography variant={isMobile ? "h6" : "h5"}>
              温湿度趋势
              {device.status === 'offline' && (
                <Chip
                  label="离线数据"
                  color="warning"
                  size="small"
                  sx={{ ml: 2 }}
                />
              )}
            </Typography>
            <Box sx={{ 
              display: 'flex',
              gap: 1,
              width: { xs: '100%', sm: 'auto' }
            }}>
              <Button
                variant="outlined"
                startIcon={<FilterListIcon />}
                onClick={() => setShowFilter(!showFilter)}
                fullWidth={isMobile}
                size={isMobile ? "small" : "medium"}
              >
                筛选
              </Button>
              <Button
                variant="outlined"
                startIcon={<DownloadIcon />}
                onClick={handleExportData}
                fullWidth={isMobile}
                size={isMobile ? "small" : "medium"}
                disabled={filteredData.length === 0}
              >
                导出
              </Button>
            </Box>
          </Box>

          {device.status === 'offline' && (
            <Alert severity="info" sx={{ mb: 2 }}>
              设备当前离线，显示历史数据
            </Alert>
          )}

          {showFilter && (
            <Box sx={{ 
              mb: 2,
              p: 2,
              bgcolor: 'background.default',
              borderRadius: 1
            }}>
              <Grid container spacing={2}>
                <Grid item xs={12} sm={6}>
                  <LocalizationProvider dateAdapter={AdapterDateFns}>
                    <DatePicker
                      label="开始日期"
                      value={dateRange.startDate ? parseISO(dateRange.startDate) : null}
                      onChange={(date) => handleDateRangeChange('startDate', date ? format(date, 'yyyy-MM-dd') : '')}
                      slotProps={{
                        textField: {
                          fullWidth: true,
                          size: isMobile ? "small" : "medium"
                        }
                      }}
                    />
                  </LocalizationProvider>
                </Grid>
                <Grid item xs={12} sm={6}>
                  <LocalizationProvider dateAdapter={AdapterDateFns}>
                    <DatePicker
                      label="结束日期"
                      value={dateRange.endDate ? parseISO(dateRange.endDate) : null}
                      onChange={(date) => handleDateRangeChange('endDate', date ? format(date, 'yyyy-MM-dd') : '')}
                      slotProps={{
                        textField: {
                          fullWidth: true,
                          size: isMobile ? "small" : "medium"
                        }
                      }}
                    />
                  </LocalizationProvider>
                </Grid>
                <Grid item xs={12}>
                  <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
                    <Button
                      variant="outlined"
                      onClick={handleResetFilters}
                      size={isMobile ? "small" : "medium"}
                    >
                      重置
                    </Button>
                    <Button
                      variant="contained"
                      onClick={applyFilters}
                      size={isMobile ? "small" : "medium"}
                    >
                      应用
                    </Button>
                  </Box>
                </Grid>
              </Grid>
            </Box>
          )}

          <Box sx={{ 
            height: { xs: 300, sm: 400, md: 500 },
            width: '100%',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            '& .recharts-wrapper': {
              margin: '0 auto'
            }
          }}>
            {filteredData.length > 0 ? (
              <TemperatureHumidityChart data={filteredData} />
            ) : (
              <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
                <Typography variant="h6" color="text.secondary">
                  {device.status === 'offline' ? '暂无历史数据' : '暂无数据'}
                </Typography>
              </Box>
            )}
          </Box>
        </CardContent>
      </Card>
    );
  };

  // 优化加载状态显示
  if (loading) {
    return (
      <Box sx={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center',
        minHeight: '60vh',
        width: '100%'
      }}>
        <CircularProgress size={isMobile ? 40 : 60} />
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ 
        mt: { xs: 2, sm: 3 }, 
        p: { xs: 2, sm: 3 }, 
        bgcolor: 'error.light',
        borderRadius: 2,
        width: '100%'
      }}>
        <Typography color="error" variant={isMobile ? "body1" : "h6"}>{error}</Typography>
      </Box>
    );
  }

  if (!device) {
    return (
      <Box sx={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center',
        minHeight: '60vh',
        width: '100%'
      }}>
        <Typography variant="h6" color="text.secondary">设备不存在</Typography>
      </Box>
    );
  }

  const renderConfigDialog = () => (
    <Dialog
      open={openConfigDialog}
      onClose={() => setOpenConfigDialog(false)}
      maxWidth="md"
      fullWidth
    >
      <DialogTitle>
        设备配置
        {device?.status === 'offline' && (
          <Chip
            label="设备离线"
            color="warning"
            size="small"
            sx={{ ml: 2 }}
          />
        )}
      </DialogTitle>
      <DialogContent>
        {device?.status === 'offline' && (
          <Alert severity="warning" sx={{ mb: 2 }}>
            设备当前离线，配置将在设备上线时自动更新
          </Alert>
        )}
        <Tabs
          value={configTab}
          onChange={(_, newValue) => setConfigTab(newValue)}
          sx={{ mb: 2 }}
        >
          <Tab label="基本设置" />
          <Tab label="报警阈值" />
          <Tab label="网络设置" />
        </Tabs>
        {/* 配置表单内容 */}
      </DialogContent>
      <DialogActions>
        <Button onClick={() => setOpenConfigDialog(false)}>取消</Button>
        <Button
          onClick={handleSaveConfig}
          variant="contained"
          disabled={loading}
          startIcon={loading ? <CircularProgress size={20} /> : null}
        >
          保存配置
        </Button>
      </DialogActions>
    </Dialog>
  );

  return (
    <Box sx={{ p: { xs: 2, sm: 3 } }}>
      {/* 顶部导航和标题 */}
      <Box sx={{ 
        display: 'flex', 
        alignItems: 'center', 
        mb: { xs: 2, sm: 3 },
        gap: 2
      }}>
        <IconButton 
          onClick={() => navigate('/devices')}
          size={isMobile ? "small" : "medium"}
        >
          <ArrowBackIcon />
        </IconButton>
        <Typography 
          variant={isMobile ? "h5" : "h4"}
          sx={{ fontWeight: 600 }}
        >
          {device.name}
        </Typography>
        <Chip
          icon={device.status === 'online' ? <WifiIcon /> : <WifiOffIcon />}
          label={device.status === 'online' ? '在线' : '离线'}
          color={device.status === 'online' ? 'success' : 'error'}
          size={isMobile ? "small" : "medium"}
          sx={{ ml: 'auto' }}
        />
      </Box>

      {/* 设备信息卡片 */}
      <Grid container spacing={2} sx={{ mb: { xs: 2, sm: 3 } }}>
        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                设备ID
              </Typography>
              <Typography variant="body1">
                {device.deviceId}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                设备类型
              </Typography>
              <Typography variant="body1">
                {device.type}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                最后心跳
              </Typography>
              <Typography variant="body1">
                {device.lastHeartbeat ? new Date(device.lastHeartbeat).toLocaleString() : '未知'}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* 数据图表和过滤器 */}
      {renderDataChart()}

      {/* 数据表格 */}
      <Card sx={{ mb: { xs: 2, sm: 3 } }}>
        <CardContent>
          <Box sx={{ 
            display: 'flex', 
            justifyContent: 'space-between',
            alignItems: 'center',
            mb: 2
          }}>
            <Typography variant={isMobile ? "h6" : "h5"}>
              历史数据
            </Typography>
          </Box>
          <TableContainer sx={{ maxHeight: 400 }}>
            <Table stickyHeader size={isMobile ? "small" : "medium"}>
              <TableHead>
                <TableRow>
                  <TableCell>时间</TableCell>
                  <TableCell align="right">温度 (°C)</TableCell>
                  <TableCell align="right">湿度 (%)</TableCell>
                  <TableCell align="right">电池电量 (%)</TableCell>
                  <TableCell align="right">信号强度 (dBm)</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {filteredData.map((data, index) => (
                  <TableRow key={index}>
                    <TableCell>
                      {format(parseISO(data.timestamp), 'yyyy-MM-dd HH:mm:ss')}
                    </TableCell>
                    <TableCell align="right">{data.data.temperature}</TableCell>
                    <TableCell align="right">{data.data.humidity}</TableCell>
                    <TableCell align="right">{data.data.battery}</TableCell>
                    <TableCell align="right">{data.data.signal}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </CardContent>
      </Card>

      {/* 设备操作按钮 */}
      {renderDeviceActions()}

      {/* 密码修改对话框 */}
      <Dialog 
        open={openPasswordDialog} 
        onClose={() => setOpenPasswordDialog(false)}
        fullWidth
        maxWidth="sm"
      >
        <DialogTitle>修改设备密码</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="新密码"
            type={showPassword ? 'text' : 'password'}
            fullWidth
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    onClick={() => setShowPassword(!showPassword)}
                    edge="end"
                  >
                    {showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
            size={isMobile ? "small" : "medium"}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenPasswordDialog(false)}>取消</Button>
          <Button onClick={handleUpdatePassword} variant="contained">
            确认
          </Button>
        </DialogActions>
      </Dialog>

      {/* 确认对话框 */}
      <Dialog
        open={openConfirmDialog}
        onClose={() => setOpenConfirmDialog(false)}
        fullWidth
        maxWidth="sm"
      >
        <DialogTitle>
          {confirmAction === 'restart' ? '重启设备' : '更新固件'}
        </DialogTitle>
        <DialogContent>
          <Typography>
            {confirmAction === 'restart'
              ? '确定要重启设备吗？'
              : '确定要更新设备固件吗？此操作可能需要几分钟时间。'}
          </Typography>
          {confirmAction === 'update' && (
            <Box sx={{ mt: 2 }}>
              <input
                type="file"
                accept=".bin"
                onChange={handleFileSelect}
                style={{ display: 'none' }}
                ref={fileInputRef}
              />
              <Button
                variant="outlined"
                startIcon={<UploadIcon />}
                onClick={() => fileInputRef.current?.click()}
                fullWidth
                size={isMobile ? "small" : "medium"}
              >
                选择固件文件
              </Button>
              {firmwareFile && (
                <Typography variant="body2" sx={{ mt: 1 }}>
                  已选择: {firmwareFile.name}
                </Typography>
              )}
              {isUpdating && (
                <Box sx={{ mt: 2 }}>
                  <LinearProgress variant="determinate" value={updateProgress} />
                  <Typography variant="body2" sx={{ mt: 1 }}>
                    更新进度: {updateProgress}%
                  </Typography>
                </Box>
              )}
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenConfirmDialog(false)}>取消</Button>
          <Button
            onClick={() => {
              if (confirmAction === 'restart') {
                handleSendCommand('restart');
              } else if (confirmAction === 'update' && firmwareFile) {
                handleUpdateFirmware();
              }
              setOpenConfirmDialog(false);
            }}
            variant="contained"
            disabled={confirmAction === 'update' && !firmwareFile}
          >
            确认
          </Button>
        </DialogActions>
      </Dialog>

      {/* 设备配置对话框 */}
      {renderConfigDialog()}

      {/* 提示消息 */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert
          onClose={() => setSnackbar({ ...snackbar, open: false })}
          severity={snackbar.severity}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default DeviceDetail; 